package com.tiyende.credit.loop.ui.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonRVVerticalScrollHelper
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.lib.common.shapeview.layout.ShapeLinearLayout
import com.lib.common.shapeview.layout.ShapeRelativeLayout
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.configs.TiyendeConfigs
import com.tiyende.credit.loop.event.TiyendeEventPointHelper
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import com.tiyende.credit.loop.weight.font.RobotoMediumEditText
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 13:54
 * @Annotation：认证流程步骤适配器
 */
class TiyendeAuthenticationStepCommonAdapter(recyclerView: RecyclerView?): CommonRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK" ->{//出生日期选择
                return R.layout.tiyende_authentication_step_common_birthday_item
            }
            "GENDER_PICK" -> {//性别
                return R.layout.tiyende_authentication_step_common_birthday_item
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                return R.layout.tiyende_authentication_step_contact_relation_item
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.tiyende_authentication_step_contact_mobile_item
            }
            "SELECT" -> {//选择
                return R.layout.tiyende_authentication_step_common_choose_item
            }
            else -> {//输入框
                return R.layout.tiyende_authentication_step_common_input_item
            }
        }
    }

    override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.authStepSelect)//选择
        helper.setItemChildClickListener(R.id.authStepContactImage)//选择联系人
        helper.setItemChildClickListener(R.id.authStepMobile)
    }

    override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val authStepTitle = helper.getTextView(R.id.authStepTitle)
        var showTitle = model.optString("title")
        if (TiyendeConfigs.isSwahili()){
            showTitle = model.optString("title_sw")
        }
        authStepTitle.text = findKeywordColor(Color.parseColor("#FFFF3939"),showTitle,"*")

        when(model.optString("action")){
            "DATE_PICK" -> {//生日选择
                showAuthStepBirthdayItemView(helper,position,model)
            }
            "SELECT" ->{//选择
                showAuthStepChooseItemView(helper,position,model)
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                showAuthStepContactRelationItemView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showAuthStepContactMobileItemView(helper,position,model)
            }
            "GENDER_PICK" -> {//性别
                showAuthStepBirthdayItemView(helper,position,model)
            }
            else -> {//输入框
                showAuthStepInputItemView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showAuthStepInputItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val inputLayout = helper.getView<ShapeLinearLayout>(R.id.authenticationStepInputLayout)
        //提示语
        val authStepEdit = helper.getView<RobotoMediumEditText>(R.id.authStepEdit)
        var showHint = model.optString("hint")
        if (TiyendeConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        authStepEdit.setHint(showHint)
        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            selectItem?.let {
                showText = selectItem.optString("title")
            }
        }
        authStepEdit.setText(showText)
        authStepEdit.setInputFocusChangeListener(object : RobotoMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus){
                    inputLayout.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF3ED9AB"))
                        .intoBackground()
                } else {
                    inputLayout.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF334155"))
                        .intoBackground()
                }
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                TiyendeEventPointHelper.addEventPointRequestAction(eventType,remark)
            }
        })

        authStepEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepEdit.clearFocus()
                true
            }
            false
        }
        authStepEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 生日选择
     */
    private fun showAuthStepBirthdayItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (TiyendeConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepSelectText = helper.getTextView(R.id.authStepSelectText)
        authStepSelectText.setHint(showHint)
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            var showTitle = selectItem.optString("title")
            if (TiyendeConfigs.isSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            authStepSelectText.text = showTitle
        }

        val authStepSelectImage = helper.getImageView(R.id.authStepSelectImage)
        authStepSelectImage.setImageResource(R.mipmap.tiyende_activity_authentication_step_select_icon)
    }

    /**
     * 选择类型
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun showAuthStepChooseItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val recyclerView = helper.getView<RecyclerView>(R.id.recyclerViewChild)
        val layoutManager = LinearLayoutManager(mContext)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        recyclerView.layoutManager = layoutManager
        val chooseChildAdapter = TiyendeAuthenticationStepChooseChildItemAdapter(recyclerView)
        recyclerView.adapter = chooseChildAdapter
        recyclerView.itemAnimator = DefaultItemAnimator()
        chooseChildAdapter.setOnItemChildClickListener{ _, childView, position ->
            val item = chooseChildAdapter.getItem(position)
            if (item.optBoolean("isSelected",false)){
                return@setOnItemChildClickListener
            }
            chooseChildAdapter.data.forEach {
                it.put("isSelected",false)
            }
            item.put("isSelected",true)
            model.put("selectItem",item)
            chooseChildAdapter.notifyDataSetChanged()

            val subRemark = item.optString("value")
            TiyendeEventPointHelper.addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,model.optString("paramName")),subRemark)
        }
        val childList = arrayListOf<JSONObject>()
        val dataArray = model.optJSONArray("values")
        if (dataArray != null) {
            for (i in 0..<dataArray.length()) {
                childList.add(dataArray.optJSONObject(i))
            }
        }
        chooseChildAdapter.data = childList
    }

    /**
     * 联系人关系
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun showAuthStepContactRelationItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val recyclerView = helper.getView<RecyclerView>(R.id.recyclerViewChild)
        val layoutManager = LinearLayoutManager(mContext)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        recyclerView.layoutManager = layoutManager
        val chooseChildAdapter = TiyendeAuthenticationStepChooseChildItemAdapter(recyclerView)
        recyclerView.adapter = chooseChildAdapter
        recyclerView.itemAnimator = DefaultItemAnimator()
        chooseChildAdapter.setOnItemChildClickListener{ _, _, position ->
            val item = chooseChildAdapter.getItem(position)
            if (item.optBoolean("isSelected",false)){
                return@setOnItemChildClickListener
            }
            chooseChildAdapter.data.forEach {
                it.put("isSelected",false)
            }
            item.put("isSelected",true)
            item.put("position",position)

            var isNotifyDataSetChangedParentAdapter = false
            //判断是否已经选择Other
            if (model.has("selectItem")){
                val selectItem = model.getJSONObject("selectItem")
                if (selectItem.optString("title") == model.optString("relationOtherKey")){
                    selectItem.put("otherValue","")
                    isNotifyDataSetChangedParentAdapter = true
                }
            }
            model.put("selectItem",item)
            chooseChildAdapter.notifyDataSetChanged()
            //上一次选中Other，切换需要刷新 || 本次关系选择Other时才刷新整个Adapter
            if (isNotifyDataSetChangedParentAdapter || item.optString("title") == model.optString("relationOtherKey")){
                notifyDataSetChanged()
            }

            val subRemark = item.optString("value")
            TiyendeEventPointHelper.addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,model.optString("paramName")),subRemark)
        }
        val childList = arrayListOf<JSONObject>()
        val dataArray = model.optJSONArray("values")
        if (dataArray != null) {
            for (i in 0..<dataArray.length()) {
                childList.add(dataArray.optJSONObject(i))
            }
        }
        chooseChildAdapter.data = childList

        val relationEditLayout = helper.getView<ShapeLinearLayout>(R.id.relationEditLayout)
        val editRelationOther = helper.getView<RobotoMediumEditText>(R.id.editRelationOther)
        editRelationOther.setHint(model.optString("relationOtherHint"))
        relationEditLayout.visibility = View.GONE

        var showOtherValue = ""
        var showTitle = ""
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            CommonRVVerticalScrollHelper.newInstance(recyclerView).scrollToPosition(selectItem.optInt("position"))
            showTitle = selectItem.optString("title")
            if (showTitle == model.optString("relationOtherKey")){
                relationEditLayout.visibility = View.VISIBLE
                if (selectItem.has("otherValue")){
                    showOtherValue = selectItem.optString("otherValue","")
                }
            }
        }

        //关系为“Other”时，输入框允许输入
        editRelationOther.isEnabled = showTitle == model.optString("relationOtherKey")
        editRelationOther.setText(showOtherValue)
        editRelationOther.setInputFocusChangeListener(object : RobotoMediumEditText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus){
                    relationEditLayout.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF3ED9AB"))
                        .intoBackground()
                } else {
                    relationEditLayout.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF334155"))
                        .intoBackground()
                }
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}_Other")
                }
                TiyendeEventPointHelper.addEventPointRequestAction(eventType,remark)
            }
        })
        editRelationOther.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editRelationOther.clearFocus()
                true
            }
            false
        }

        editRelationOther.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (model.has("selectItem")){
                    val selectItem = model.getJSONObject("selectItem")
                    selectItem.put("otherValue",s.toString())
                }
            }
        })
    }

    /**
     * 联系电话
     */
    private fun showAuthStepContactMobileItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val authStepSelect = helper.getView<ShapeRelativeLayout>(R.id.authStepSelect)
        //提示语
        var showHint = model.optString("hint")
        if (TiyendeConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepMobile = helper.getTextView(R.id.authStepMobile)
        authStepMobile.setHint(showHint)
        val authStepMobileEdit = helper.getView<RobotoMediumEditText>(R.id.authStepMobileEdit)
        authStepMobileEdit.setHint(showHint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            authStepMobile.text = showValue
            authStepMobileEdit.setText(showValue)
        }
        authStepMobileEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepMobileEdit.clearFocus()
                true
            }
            false
        }
        authStepMobileEdit.setInputFocusChangeListener(object : RobotoMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus){
                    authStepSelect.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF3ED9AB"))
                        .intoBackground()
                } else {
                    authStepSelect.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF334155"))
                        .intoBackground()
                }
            }
            override fun onCompleteAction(v: View?, remark: String?) {
                var eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                TiyendeEventPointHelper.addEventPointRequestAction(eventType,remark)
            }
        })
        authStepMobileEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否是审核账号
        val isAdmin = TiyendeSharedHelper.queryTiyendeSharedBoolean(TiyendeSharedKey.TIYENDE_IS_CONFIG_ACCOUNT)
        if(isAdmin){//审核账号 - 允许输入或选择
            authStepMobile.visibility = View.GONE
            authStepMobileEdit.visibility = View.VISIBLE
        } else {//非审核账号只能选择
            //设备是否支持通讯录选择联系人
            if (model.optBoolean("isContactPick")){
                authStepMobile.visibility = View.VISIBLE
                authStepMobileEdit.visibility = View.GONE
            } else {
                authStepMobile.visibility = View.GONE
                authStepMobileEdit.visibility = View.VISIBLE
            }
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}